import { defineStore } from "pinia";
import { 
  getNotifications, 
  getUnreadCount, 
  markAsRead, 
  markAllAsRead, 
  deleteNotification,
  clearAllNotifications,
  getRealtimeNotifications
} from "@/api/notification";
import { useUserStore } from "./user";

export const useNotificationStore = defineStore("notification", {
  state: () => ({
    notifications: [],
    unreadCount: {
      total: 0,
      pending: 0,
      review: 0,
      alert: 0,
      system: 0,
      order: 0,
      finance: 0,
      interaction: 0,
    },
    loading: false,
    initialized: false,
    pollingTimer: null,
  }),

  getters: {
    hasUnread: (state) => state.unreadCount.total > 0,
  },

  actions: {
    /**
     * 初始化通知模块
     */
    async initialize() {
      if (this.initialized) return;
      
      const userStore = useUserStore();
      if (!userStore.isLoggedIn) return;

      try {
        await this.fetchUnreadCount();
        this.initialized = true;
        this.startPolling();
      } catch (error) {
        console.error("初始化通知模块失败:", error);
      }
    },

    /**
     * 获取未读通知数量
     */
    async fetchUnreadCount() {
      const userStore = useUserStore();
      if (!userStore.isLoggedIn) return;

      try {
        const { data } = await getUnreadCount();
        this.unreadCount = data;
      } catch (error) {
        console.error("获取未读通知数量失败:", error);
      }
    },

    /**
     * 获取通知列表
     * @param {Object} params 查询参数
     */
    async fetchNotifications(params = {}) {
      const userStore = useUserStore();
      if (!userStore.isLoggedIn) return { total: 0, list: [] };

      this.loading = true;
      try {
        const response = await getNotifications(params);
        // 处理直接返回数组的情况
        if (Array.isArray(response.data)) {
          this.notifications = response.data;
          return { 
            total: response.data.length, 
            list: response.data 
          };
        } 
        // 处理标准格式{list, total}的情况 
        else if (response.data && response.data.list) {
          this.notifications = response.data.list;
          return response.data;
        }
        // 兜底处理
        else {
          console.warn("通知数据格式不符合预期:", response);
          this.notifications = [];
          return { total: 0, list: [] };
        }
      } catch (error) {
        console.error("获取通知列表失败:", error);
        return { total: 0, list: [] };
      } finally {
        this.loading = false;
      }
    },

    /**
     * 获取实时通知
     */
    async fetchRealtimeNotifications() {
      const userStore = useUserStore();
      if (!userStore.isLoggedIn) return [];

      try {
        const { data } = await getRealtimeNotifications();
        if (data && data.length > 0) {
          // 更新未读数量
          await this.fetchUnreadCount();
          
          // 将新通知添加到通知中心
          this.showNotifications(data);
        }
        return data;
      } catch (error) {
        console.error("获取实时通知失败:", error);
        return [];
      }
    },

    /**
     * 显示通知
     * @param {Array} notifications 通知列表
     */
    showNotifications(notifications) {
      if (!notifications || !notifications.length) return;
      
      // 这里不直接处理通知，而是发送一个自定义事件
      // 由GlobalNotification组件来处理这些通知的显示
      const event = new CustomEvent("show-notifications", {
        detail: { notifications }
      });
      window.dispatchEvent(event);
    },

    /**
     * 标记单个通知为已读
     * @param {number} id 通知ID
     */
    async markAsRead(id) {
      try {
        await markAsRead(id);
        
        // 更新本地状态
        const index = this.notifications.findIndex(n => n.id === id);
        if (index > -1) {
          this.notifications[index].isRead = true;
        }
        
        // 更新未读数量
        await this.fetchUnreadCount();
        return true;
      } catch (error) {
        console.error("标记通知为已读失败:", error);
        return false;
      }
    },

    /**
     * 标记所有通知为已读
     */
    async markAllAsRead() {
      try {
        await markAllAsRead();
        
        // 更新本地状态
        this.notifications.forEach(n => n.isRead = true);
        
        // 更新未读数量
        this.unreadCount = {
          total: 0,
          pending: 0,
          review: 0,
          alert: 0,
          system: 0,
          order: 0,
          finance: 0,
          interaction: 0,
        };
        
        return true;
      } catch (error) {
        console.error("标记所有通知为已读失败:", error);
        return false;
      }
    },

    /**
     * 删除单个通知
     * @param {number} id 通知ID
     */
    async deleteNotification(id) {
      try {
        await deleteNotification(id);
        
        // 更新本地状态
        const index = this.notifications.findIndex(n => n.id === id);
        if (index > -1) {
          // 如果是未读通知被删除，需要更新未读数量
          if (!this.notifications[index].isRead) {
            await this.fetchUnreadCount();
          }
          this.notifications.splice(index, 1);
        }
        
        return true;
      } catch (error) {
        console.error("删除通知失败:", error);
        return false;
      }
    },

    /**
     * 清空所有通知
     */
    async clearAllNotifications() {
      try {
        await clearAllNotifications();
        
        // 更新本地状态
        this.notifications = [];
        this.unreadCount = {
          total: 0,
          pending: 0,
          review: 0,
          alert: 0,
          system: 0,
          order: 0,
          finance: 0,
          interaction: 0,
        };
        
        return true;
      } catch (error) {
        console.error("清空所有通知失败:", error);
        return false;
      }
    },

    /**
     * 开始轮询新通知
     */
    startPolling() {
      // 清除现有的定时器
      this.stopPolling();
      
      // 设置新的定时器，每30秒轮询一次
      this.pollingTimer = setInterval(() => {
        this.fetchRealtimeNotifications();
      }, 30000);
    },

    /**
     * 停止轮询
     */
    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
        this.pollingTimer = null;
      }
    },

    /**
     * 重置状态
     */
    reset() {
      this.stopPolling();
      this.notifications = [];
      this.unreadCount = {
        total: 0,
        pending: 0,
        review: 0,
        alert: 0,
        system: 0,
        order: 0,
        finance: 0,
        interaction: 0,
      };
      this.initialized = false;
    },
  },
}); 